﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using PaypalConverterSite;
using System.Data;
using System.Reflection;
using System.Drawing;
using PaypalConverterSite.IIFService;
namespace PaypalConverterSite
{
    public partial class Processor : System.Web.UI.Page
    {
        ProcessorServiceClient processorService;
        string wizardName = "tblPayPal";

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            lblError.Visible = false;
            lblRepError.Visible = false;
            if (!this.IsPostBack && !string.IsNullOrEmpty(Request.QueryString["Error"]))
            {
                ShowError(); //If redirection is for displaying error
            }
        }

        protected void Page_Error(object sender, EventArgs e)
        {
            //If any error in the page, redirect to the first page and display the error
            Server.ClearError();
            string pageName = Path.GetFileName(Request.Path);
            Response.Redirect(pageName + "?Error=true");
        }

        private void Page_PreRender(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "start", "LoadWizard('" + wizardName + "');", true);
        }

        protected void PaypalNext_Click(object sender, EventArgs e)
        {
            string pay = PayPalFile;
            wizardName = "tblCategories";
        }

        protected void CategoriesNext_Click(object sender, EventArgs e)
        {
            wizardName = "tblOptions";
            LoadOptions();
        }

        protected void Process_Click(object sender, EventArgs e)
        {
            wizardName = "tblOptions";
            ProcessData();
        }


        protected void GotoPaypal_Click(object sender, EventArgs e)
        {
            //LoadGrid();
            wizardName = "tblPaypal";
        }

        protected void GotoCategories_Click(object sender, EventArgs e)
        {
            //LoadGrid();
            wizardName = "tblCategories";
        }

        protected void grvPaypal_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView row = e.Row.DataItem as DataRowView;
                if ((int)row["IsChanged"] == 1)
                {
                    e.Row.BackColor = CommonUtility.ReplaceBackColor;
                }
                else if ((int)row["IsChanged"] > 1)
                {
                    e.Row.BackColor = Color.Yellow;
                }

            }
        }

        protected void Save_Click(object sender, EventArgs e)
        {
            ExportCSV();
        }

        protected void ddlSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowMatch();
        }

        #endregion

        #region Methods

        private void LoadOptions()
        {
            processorService = new ProcessorServiceClient();
            string file = PayPalFile;
            ddlSearch.DataSource = processorService.GetAccountTypes(file);
            ddlSearch.DataBind();

            ddlMap.Items.Clear();
            ddlMap.Items.Add(string.Empty);
            ddlMap.AppendDataBoundItems = true;
            ddlMap.DataSource = processorService.GetCategories(Categories);
            ddlMap.DataBind();
            DataTable data;
            data = processorService.ProcessData(file, string.Empty, string.Empty, string.Empty);
            PayPalData = data;
            grvPaypal.DataSource = data;
            grvPaypal.DataBind();
        }

        private void ProcessData()
        {
            if (ddlMap.SelectedIndex > 0)
            {
                DataTable data;
                processorService = new ProcessorServiceClient();
                data = processorService.ReplaceData(PayPalData, SearchFor, txtFor.Text, ReplaceWith, chkStepBy.Checked);
                PayPalData = data;
                grvPaypal.DataSource = data;
                grvPaypal.DataBind();
                ShowMatch();
                ddlMap.SelectedIndex = 0;
            }
            else
            {
                lblRepError.Visible = true;
            }
        }

        private string PayPalFile
        {
            get
            {
                if (fupPaypal.PostedFile != null && fupPaypal.PostedFile.InputStream.Length > 0)
                {
                    Stream theStream = fupPaypal.PostedFile.InputStream;
                    StreamReader sr = new StreamReader(theStream);
                    string file = sr.ReadToEnd();
                    Session[MethodInfo.GetCurrentMethod().Name] = file;
                    ViewState["FileName"] = fupPaypal.PostedFile.FileName;
                }
                return Session[MethodInfo.GetCurrentMethod().Name].ToString();
            }
        }

        private string Categories
        {
            get
            {
                if (fupCategories.PostedFile != null && fupCategories.PostedFile.InputStream.Length > 0)
                {
                    Stream theStream = fupCategories.PostedFile.InputStream;
                    StreamReader sr = new StreamReader(theStream);
                    string file = sr.ReadToEnd();
                    Session[MethodInfo.GetCurrentMethod().Name] = file;
                }
                return Session[MethodInfo.GetCurrentMethod().Name].ToString();
            }
        }


        private void ShowMatch()
        {
            DataRow[] matches = PayPalData.Select(PayPalData.Columns[2].ColumnName + " = '" + SearchFor + "'");

            if (matches != null && matches.Length > 0)
            {
                MatchText = matches[0][3].ToString();
                txtRemaining.Text = matches.Length.ToString();
                foreach (GridViewRow row in grvPaypal.Rows)
                {
                    if (row.Cells[2].Text.Replace("&quot;", "\"") == SearchFor && row.Cells[3].Text.Replace("&quot;", "\"").StartsWith(txtFor.Text))
                    {
                        row.BackColor = CommonUtility.MatchBackColor;
                    }
                }
            }
            else
            {
                txtFor.Text = string.Empty;
                txtRemaining.Text = 0.ToString();
            }
            wizardName = "tblOptions";
        }

         private DataTable PayPalData
        {
            get
            {
                return (DataTable)Session["PayPalData"];
            }
            set
            {
                Session["PayPalData"] = value;
            }
        }

        private string SearchFor
        {
            get
            {
                if (ddlSearch.SelectedIndex == 0)
                    return string.Empty;
                else
                    return ddlSearch.SelectedItem.Text;
            }
        }

        private string ReplaceWith
        {
            get
            {
                if (ddlMap.SelectedIndex == 0)
                    return string.Empty;
                else
                    return ddlMap.SelectedItem.Text;
            }
        }

        private void ExportCSV()
        {
            processorService = new ProcessorServiceClient();
            string file = PayPalFile;

            string exportDate = processorService.GetExportDataFile(PayPalData);

            Response.Clear();
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.IIF", Path.GetFileNameWithoutExtension(ViewState["FileName"].ToString())));
            Response.ContentType = "application/ms-excel";
            Response.AddHeader("Pragma", "public");
            Response.Write(exportDate);
            Response.End();
        }

        private void ShowError()
        {
            lblError.Visible = true;
            wizardName = "tblPayPal";
        }

        private string MatchText
        {
            set
            {
                txtFor.Text = value.Substring(0, Math.Min(value.Length, CommonUtility.MatchNumberOfChars));
            }
        }

        #endregion
    }
}

